﻿using BBCore.Application.ViewModels.Admins;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.Extensions.Localization;

namespace BBCore.Server.Components.Pages.Admins
{
    public partial class Login
    {
        private LoginVo LoginVo { get; set; } = new LoginVo();
        private async Task OnValidSubmit(EditContext arg)
        {
            var document = await AjaxService.InvokeAsync(new AjaxOption()
            {
                Url = "/api/Account/Login",
                Data = LoginVo
            });
            if (document?.RootElement.GetProperty("code").GetInt32() == 20000)
            {
                await AjaxService.Goto("/");
            }
            else
            {
                await SwalService.Show(new SwalOption()
                {
                    Category = SwalCategory.Error,
                    Content = document?.RootElement.GetProperty("message").GetString() ?? "系统异常",
                    Title = "登录失败"
                });
            }

        }
        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            var user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;     
            if (user?.Identity?.IsAuthenticated == true)
            {
                //Cookie未失效情况下跳转到主页
                NavigationManager.NavigateTo("/");
            }
        }
    }
}
